package com.uzai.console.service.profit.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.profit.ladderratio.LadderRatioIdDto;
import com.uzai.console.dto.profit.ladderratio.LadderRatioIdListDto;
import com.uzai.console.dto.profit.ladderratio.LadderRatioInfoDto;
import com.uzai.console.dto.profit.ladderratio.LadderRatioQuery;
import com.uzai.console.dto.profit.ladderratiogroup.LadderRatioGroupIdDto;
import com.uzai.console.dto.profit.ladderratiogroup.LadderRatioGroupInfoDto;
import com.uzai.console.dto.profit.ladderratiogroup.LadderRatioGroupQuery;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.entity.LadderRatio;
import com.uzai.console.entity.LadderRatioGroup;
import com.uzai.console.mapper.LadderRatioGroupMapper;
import com.uzai.console.mapper.LadderRatioMapper;
import com.uzai.console.mapper.WechatUserMapper;
import com.uzai.console.service.profit.LadderRatioService;
import com.uzai.console.vo.profit.ladderratio.LadderRatioInfoVo;
import com.uzai.console.vo.profit.ladderratiogroup.LadderRatioGroupInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
@Slf4j
public class LadderRatioServiceImpl implements LadderRatioService {

    @Autowired
    private LadderRatioMapper ladderRatioMapper;
    @Autowired
    private LadderRatioGroupMapper ladderRatioGroupMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;

   /**
     * 分页查询阶梯规则列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param query
     * @return null
     */
    public Page<LadderRatioInfoVo> findLadderRatioList(LadderRatioQuery query){
        //新建返回到页面的LIST对象
        List<LadderRatioInfoVo> ladderRatioInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<LadderRatio> page = new Page<>();

        //排序
        List<OrderItem> orderItemList = new ArrayList<>();
        orderItemList.add(OrderItem.asc("group_id"));
        orderItemList.add(OrderItem.asc("min_commission"));
        query.setOrderItemList(orderItemList);

        query.convert(page);
        List<LadderRatio> ladderRatioList = ladderRatioMapper.findByList(page, query);

        if(ladderRatioList != null){
            for (LadderRatio ladderRatio : ladderRatioList){
                LadderRatioInfoVo ladderRatioInfoVo = new LadderRatioInfoVo();
                BeanUtils.copyProperties(ladderRatio, ladderRatioInfoVo);
                //阶梯规则比例名称
                LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(ladderRatio.getGroupId(), ladderRatio.getMerId());
                if(ladderRatioGroup != null){
                    ladderRatioInfoVo.setGroupName(ladderRatioGroup.getName());
                }
                ladderRatioInfoVoList.add(ladderRatioInfoVo);
            }
        }

        //返回到页面分页对象
        Page<LadderRatioInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(ladderRatioInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

   /**
     * 查询阶梯规则详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioIdDto
     * @return null
     */
    public LadderRatioInfoVo findLadderRatioInfo(LadderRatioIdDto ladderRatioIdDto){
        if(ladderRatioIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        LadderRatio ladderRatio = ladderRatioMapper.selectById(ladderRatioIdDto.getId(), ladderRatioIdDto.getMerId());

        if(ladderRatio == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该阶梯规则不存在");
        }

        LadderRatioInfoVo ladderRatioInfoVo =  new LadderRatioInfoVo();

        BeanUtils.copyProperties(ladderRatio, ladderRatioInfoVo);

        return ladderRatioInfoVo;
    }

   /**
     * 添加阶梯规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioInfoDto
     * @return null
     */
    public void addLadderRatio(LadderRatioInfoDto ladderRatioInfoDto){
        if(ladderRatioInfoDto.getGroupId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择阶梯分组");
        }

        if(ladderRatioInfoDto.getMinCommission() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入最小佣金");
        }
        if(ladderRatioInfoDto.getMaxCommission() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入最大佣金");
        }
        //最大佣金必须大于等于最小佣金
        if(ladderRatioInfoDto.getMaxCommission().doubleValue() <= ladderRatioInfoDto.getMinCommission().doubleValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大佣金值必须超过最小佣金值");
        }
        //验证佣金范围是否与数据中存在交叉
        LadderRatio ladderRatio_commission = ladderRatioMapper.selectByCommission(ladderRatioInfoDto);
        if(ladderRatio_commission != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分组下佣金范围存在重复");
        }

        if(ladderRatioInfoDto.getRatio() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入分成比例");
        }

        LadderRatio ladderRatio = new LadderRatio();
        BeanUtils.copyProperties(ladderRatioInfoDto, ladderRatio);
        Integer now = DateUtil.getNowTime();
        ladderRatio.setId(IdWorker.getId());
        ladderRatio.setCreateTime(now);
        ladderRatio.setUpdateTime(now);
        ladderRatioMapper.insert(ladderRatio);
    }

   /**
     * 修改阶梯规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioInfoDto
     * @return null
     */
    public void updateLadderRatio(LadderRatioInfoDto ladderRatioInfoDto){

        if(ladderRatioInfoDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员id");
        }

        if(ladderRatioInfoDto.getGroupId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择阶梯分组");
        }

        if(ladderRatioInfoDto.getMinCommission() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入最小佣金");
        }

        if(ladderRatioInfoDto.getMaxCommission() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入最大佣金");
        }

        if(ladderRatioInfoDto.getRatio() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入分成比例");
        }

        //最大佣金必须大于等于最小佣金
        if(ladderRatioInfoDto.getMaxCommission().doubleValue() <= ladderRatioInfoDto.getMinCommission().doubleValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大佣金值必须超过最小佣金值");
        }
        //验证佣金范围是否与数据中存在交叉
        LadderRatio ladderRatio_commission = ladderRatioMapper.selectByCommission(ladderRatioInfoDto);
        if(ladderRatio_commission != null && ladderRatio_commission.getId().longValue() != ladderRatioInfoDto.getId().longValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分组下佣金范围存在重复");
        }

        LadderRatio ladderRatio = ladderRatioMapper.selectById(ladderRatioInfoDto.getId(), ladderRatioInfoDto.getMerId());
        if(ladderRatio != null){
            ladderRatio.setGroupId(ladderRatioInfoDto.getGroupId());
            ladderRatio.setMinCommission(ladderRatioInfoDto.getMinCommission());
            ladderRatio.setMaxCommission(ladderRatioInfoDto.getMaxCommission());
            ladderRatio.setRatio(ladderRatioInfoDto.getRatio());
            ladderRatio.setUpdateTime(DateUtil.getNowTime());
            ladderRatioMapper.update(ladderRatio);
        }
    }

   /**
     * 删除阶梯规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioIdDto
     * @return null
     */
    public void deleteLadderRatio(LadderRatioIdDto ladderRatioIdDto){

        if(ladderRatioIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员id");
        }

        //删除
        ladderRatioMapper.deleteById(ladderRatioIdDto.getId(), ladderRatioIdDto.getMerId());
    }

    /**
     *批量删除阶梯规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioIdListDto
     * @return null
     */
    public void deleteLadderRatioBatch(LadderRatioIdListDto ladderRatioIdListDto){
        List<Long> idList = ladderRatioIdListDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员id");
        }
        for (Long id : idList) {
            try {
                //删除
                ladderRatioMapper.deleteById(id, ladderRatioIdListDto.getMerId());
            }catch (Exception e){
                log.info("--删除阶梯规则失败，id={}",id);
            }
        }
    }

   /**
     * 分页查询阶梯规则分组列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioGroupQuery
     * @return null
     */
    public Page<LadderRatioGroupInfoVo> findLadderRatioGroupList(LadderRatioGroupQuery ladderRatioGroupQuery){
        //新建返回到页面的LIST对象
        List<LadderRatioGroupInfoVo> ladderRatioGroupInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<LadderRatioGroup> page = new Page<>();
        ladderRatioGroupQuery.convert(page);
        List<LadderRatioGroup> ladderRatioGroupList = ladderRatioGroupMapper.findByList(page, ladderRatioGroupQuery);

        if(ladderRatioGroupList != null){
            for (LadderRatioGroup ladderRatioGroup : ladderRatioGroupList){
                LadderRatioGroupInfoVo ladderRatioGroupInfoVo = new LadderRatioGroupInfoVo();
                BeanUtils.copyProperties(ladderRatioGroup, ladderRatioGroupInfoVo);
                ladderRatioGroupInfoVoList.add(ladderRatioGroupInfoVo);
            }
        }

        //返回到页面分页对象
        Page<LadderRatioGroupInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(ladderRatioGroupInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

   /**
     * 添加阶梯规则分组
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioGroupInfoDto
     * @return null
     */
    public void addLadderRatioGroup(LadderRatioGroupInfoDto ladderRatioGroupInfoDto){
        if(StringUtils.isBlank(ladderRatioGroupInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入分组名称");
        }
        //验证是否重名
        LadderRatioGroup ladderRatioGroup_name = ladderRatioGroupMapper.selectByName(ladderRatioGroupInfoDto.getMerId(), ladderRatioGroupInfoDto.getName());
        if(ladderRatioGroup_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该组名称已经存在");
        }

        Integer now = DateUtil.getNowTime();
        LadderRatioGroup ladderRatioGroup = new LadderRatioGroup();
        ladderRatioGroup.setId(IdWorker.getId());
        ladderRatioGroup.setMerId(ladderRatioGroupInfoDto.getMerId());
        ladderRatioGroup.setName(ladderRatioGroupInfoDto.getName());
        ladderRatioGroup.setCreateTime(now);
        ladderRatioGroup.setUpdateTime(now);
        ladderRatioGroupMapper.insert(ladderRatioGroup);
    }

   /**
     * 删除阶梯规则分组
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioGroupIdDto
     * @return null
     */
    public void deleteLadderRatioGroup(LadderRatioGroupIdDto ladderRatioGroupIdDto){
        if(ladderRatioGroupIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择id");
        }

        //查询该分组是否已经被阶梯选用
        LadderRatioQuery ladderRatioQuery = new LadderRatioQuery();
        ladderRatioQuery.setMerId(ladderRatioGroupIdDto.getMerId());
        ladderRatioQuery.setGroupId(ladderRatioGroupIdDto.getId());
        List<LadderRatio> ladderRatioList = ladderRatioMapper.findByList(ladderRatioQuery);
        if(ladderRatioList != null && ladderRatioList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分组已经被使用，不能删除");
        }

        //查询此阶梯规则组是有个人用户在定向比例当中使用，如果有就不能删除
        WechatUserQuery wechatUserQuery = new WechatUserQuery();
        wechatUserQuery.setMerId(ladderRatioGroupIdDto.getMerId());
        wechatUserQuery.setPriRewardRules(String.valueOf(ladderRatioGroupIdDto.getId()));
        Page<WechatUser> page = new Page<>();
        page.setSize(5);
        page.setCurrent(1);
        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
        //判断微信用户是否在使用
        if(wechatUserList != null && wechatUserList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此阶梯规则已经有会员定向规则中使用，不能删除");
        }

        //判断公众号是否在使用

        //判断在杀熟规则中是否使用

        //判断在分佣规则中是否使用

        ladderRatioGroupMapper.deleteById(ladderRatioGroupIdDto.getId(), ladderRatioGroupIdDto.getMerId());
    }

   /**
     * 修改阶梯规则分组
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param ladderRatioGroupInfoDto
     * @return null
     */
    public void updateLadderRatioGroup(LadderRatioGroupInfoDto ladderRatioGroupInfoDto){

        if(ladderRatioGroupInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        if(StringUtils.isBlank(ladderRatioGroupInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入分组名称");
        }

        LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(ladderRatioGroupInfoDto.getId(), ladderRatioGroupInfoDto.getMerId());
        if(ladderRatioGroup == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该类型分组不存在");
        }

        //验证新名字是否已经存在
        if(!ladderRatioGroupInfoDto.getName().equals(ladderRatioGroup.getName())){ //表示修改了组名称
            //验证新名称是否存在
            LadderRatioGroup ladderRatioGroup_name = ladderRatioGroupMapper.selectByName(ladderRatioGroupInfoDto.getMerId(), ladderRatioGroupInfoDto.getName());
            if(ladderRatioGroup_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该组名称已经存在");
            }
        }

        Integer now = DateUtil.getNowTime();
        ladderRatioGroup.setName(ladderRatioGroupInfoDto.getName());
        ladderRatioGroup.setUpdateTime(now);
        ladderRatioGroupMapper.update(ladderRatioGroup);
    }


    @Override
    @Transactional
    public void copyLadderRatioByGroup(LadderRatioGroupInfoDto ladderRatioGroupInfoDto) {
        if(ladderRatioGroupInfoDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "组id不能为空");
        }
        if(ladderRatioGroupInfoDto.getName() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分组名称不能为空");
        }

        List<LadderRatio> ladderRatioList =ladderRatioMapper.queryByGroup(ladderRatioGroupInfoDto.getId(),ladderRatioGroupInfoDto.getMerId());

        if(ladderRatioList == null|| ladderRatioList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该阶梯规则不存在");
        }


        //验证是否重名
        LadderRatioGroup ladderRatioGroup_name = ladderRatioGroupMapper.selectByName(ladderRatioGroupInfoDto.getMerId(), ladderRatioGroupInfoDto.getName());
        if(ladderRatioGroup_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该组名称已经存在");
        }

        //设置新分组
        Integer now = DateUtil.getNowTime();
        LadderRatioGroup ladderRatioGroup = new LadderRatioGroup();
        Long groupId=IdWorker.getId();
        ladderRatioGroup.setId(groupId);
        ladderRatioGroup.setMerId(ladderRatioGroupInfoDto.getMerId());
        ladderRatioGroup.setName(ladderRatioGroupInfoDto.getName());
        ladderRatioGroup.setCreateTime(now);
        ladderRatioGroup.setUpdateTime(now);
        ladderRatioGroupMapper.insert(ladderRatioGroup);

        //设置复制的阶梯规则
        ladderRatioList.forEach(it->
        {
            LadderRatio ladderRatio = new LadderRatio();
            ladderRatio.setId(IdWorker.getId());
            ladderRatio.setMerId(it.getMerId());
            ladderRatio.setGroupId(groupId);
            ladderRatio.setMinCommission(it.getMinCommission());
            ladderRatio.setMaxCommission(it.getMaxCommission());
            ladderRatio.setRatio(it.getRatio());
            ladderRatio.setCreateTime(now);
            ladderRatio.setUpdateTime(now);
            ladderRatioMapper.insert(ladderRatio);
        });


    }
}
